package com.im.linving.imsdkdal.imsdk.nimImp;

import com.im.linving.apputils.functions.Action1;
import com.im.linving.apputils.functions.Action2;
import com.im.linving.imsdkdal.imsdk.IMMessegeAction;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import java.io.File;

/**
 * @Author linyong
 * @Date 2016/11/1
 * @Time 15:16
 */
public class Nim_IMMessegeAction implements IMMessegeAction {


    /**
     *
     *  发送 文字消息
     *
     * @param userId
     * @param msgType
     * @param msg
     * @param success
     * @param fail
     */
    @Override
    public void sendTextMessge(String userId, String msgType, String msg , final Action1 success, final Action2 fail) {
        IMMessage  message = MessageBuilder.createTextMessage(userId, SessionTypeEnum.P2P, msg);
        sendMessege(success, fail, message);
    }

    /**
     *
     * 发送图片消息
     *
     * @param userId
     * @param msgType
     * @param file
     * @param fileName
     * @param success
     * @param fail
     */
    @Override
    public void sendImageMessage(String userId, String msgType, File file, String fileName, Action1 success, Action2 fail) {
        IMMessage message = MessageBuilder.createImageMessage(userId,  SessionTypeEnum.P2P, file, fileName);
        sendMessege(success, fail, message);
    }

    @Override
    public void sendAudioMessage(String userId, String msgType, File file, long time, Action1 success, Action2 fail) {
        IMMessage message = MessageBuilder.createAudioMessage(
                userId, // 聊天对象的 ID，如果是单聊，为用户帐号，如果是群聊，为群组 ID
                SessionTypeEnum.P2P, // 聊天类型，单聊或群组
                file, // 音频文件
                time // 音频持续时间，单位是ms
        );
        sendMessege(success, fail, message);
    }

    /**
     *
     * @param success
     * @param fail
     * @param message
     */
    private void sendMessege(final Action1 success, final Action2 fail, IMMessage message) {
        NIMClient.getService(MsgService.class).sendMessage(message,false).setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                success.call(aVoid);
            }

            @Override
            public void onFailed(int i) {
                fail.call(-1,"发送失败 code =  + " + i);
            }

            @Override
            public void onException(Throwable throwable) {
                fail.call(-1,"发送失败 " + throwable.toString());
                throwable.printStackTrace();
            }
        });
    }
}
